/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.student.service;

import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.student.utils.DownloadFileUtil;
import com.jeesite.modules.student.utils.ImportExcelUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.student.entity.Student;
import com.jeesite.modules.student.dao.StudentDao;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 学生表Service
 * @author 梁师豪LXH
 * @version 2021-07-17
 */
@Service
@Transactional(readOnly=false)
public class StudentService extends CrudService<StudentDao, Student> {

	/**
	 * 通过 Excel 批量导入学生信息
	 * @param file
	 * @return
	 */
	public String importData(MultipartFile file) {
		// 空null异常处理
		if (file == null){
			throw new ServiceException(text("请选择导入的数据文件！"));
		}
		int successNum = 0; int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();

		try{
			// 获取文件名
			String fileName = file.getOriginalFilename();
			// 获取文件输入流
			InputStream is = file.getInputStream();
			// 通过导入Excel工具包ImportExcelUtil得到Excel中的学生信息List
			List<Student> list = ImportExcelUtil.get(is,fileName);
			// 遍历List中的Student进行save(insert)插入数据库
			for (Student student:list) {
				this.save(student);
			}

		} catch (Exception e){
			failureNum++;
			e.printStackTrace();
		}

		if (failureNum > 0) {
			failureMsg.insert(0, "抱歉，导入失败！请先下载学生表模板再通过Excel批量导入 " );
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "通过 Excel 批量导入学生信息成功！");
		}

		return successMsg.toString();

	}


	/**
	 * 导出空白学生信息表格，用于下载学生表模板
	 * @param request
	 * @param response
	 * @return
	 */
	public void exportEmptyStudentExcel(HttpServletRequest request, HttpServletResponse response) {

		try{
			//命名下载的Excel模板，学生信息表格文件名
			String fileName = "学生表模板" + ".xls";
			//通过本地方法createStudentEmptyExcel获得Excel模板路径
			String filePath = createStudentEmptyExcel(request);
			//通过下载文件工具包DownloadFileUtil，执行下载学生表模板操作
			new DownloadFileUtil().download(filePath, fileName, request, response, false);

		}catch (Exception e) {
			e.printStackTrace();
		}

	}


	/**
	 * 获取单条数据
	 * @param student
	 * @return
	 */
	@Override
	public Student get(Student student) {
		return super.get(student);
	}
	
	/**
	 * 查询分页数据
	 * @param student 查询条件
	 * @return
	 */
	@Override
	public Page<Student> findPage(Student student) {
		return super.findPage(student);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param student
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Student student) {
		super.save(student);
	}
	
	/**
	 * 更新状态
	 * @param student
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Student student) {
		super.updateStatus(student);
	}
	
	/**
	 * 删除数据
	 * @param student
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Student student) {
		super.delete(student);
	}


	/**
	 * 创建空白学生信息表格，用于下载学生表模板
	 * @param request
	 * @return
	 */
	public String createStudentEmptyExcel(HttpServletRequest request) throws Exception{

		HSSFWorkbook wb = new HSSFWorkbook();

		HSSFSheet sheet = wb.createSheet("学生数据");

		HSSFRow row = sheet.createRow((int) 0);

		HSSFCellStyle style = wb.createCellStyle();

		style.setAlignment(HorizontalAlignment.CENTER);

		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("学生姓名");
		cell.setCellStyle(style);

		cell = row.createCell((short) 1);
		cell.setCellValue("学生性别");

		cell = row.createCell((short) 2);
		cell.setCellValue("手机号码");

		String unloadPath = request.getSession().getServletContext().getRealPath("/") + "/download/StudentEmptyExcel/";

		SimpleDateFormat autoDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		String title = autoDate.format(new Date());

		String filePath = unloadPath + title + ".xls";

		// 不存在该文件路径则自动创建mkdir
		File dirFile = new File(unloadPath);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			dirFile.mkdirs();
		}

		wb.write(new FileOutputStream(filePath));

		return filePath;

	}
	
}